import os
import sys
import re

rootDir = '..'
tgt = ""
caseSensitive = False
wordsOnly = False

#help message
if len(sys.argv) == 1:
    print("find.py [-p PATH] [-c] [-w] \"words\"")
    print("Path defaults to \"..\". -c specifies case sensitivity.")
    print("-w specifies whole words only")
    exit(-1)
#command line parser
else:
    for i in range(len(sys.argv)):
        if sys.argv[i] == "-c":
            caseSensitive = True
        if sys.argv[i] == "-w":
            wordsOnly = True
        if sys.argv[i] == "-p":
            rootDir = sys.argv[i + 1]
        if i == len(sys.argv) - 1:
            tgt = sys.argv[i]

#assemble regex
regex = tgt
if wordsOnly:
    regex = r"(^|\s)" + regex + r"($|\s)"
matcher = re.compile(regex, re.I if not caseSensitive else 0)

#file parser
for dirName, subDirs, fileList in os.walk(rootDir):
    for fname in fileList:
        f = open(dirName + os.sep + fname, 'r')
        try:            
            lineCount = 1
            headerDisplayed = False
            for line in f:                
                if matcher.search(line):
                    if not headerDisplayed:
                        print("FILE: {0}".format(fname) + os.linesep)
                    print("\tLINE {0}: {1}".format(lineCount, line.strip()) + os.linesep)
                lineCount += 1
        except UnicodeDecodeError:
            pass
        f.close()
